package com.itheima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.admin.feign.AdChannelFeign;
import com.itheima.admin.pojo.AdChannel;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.service.ApiService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.wemedia.service.impl
 */
@Service
public class ApiServiceImpl implements ApiService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private AdChannelFeign adChannelFeign;

    /**
     * 频道列表
     *
     * @return
     */
    @Override
    public List<AdChannel> getChannelList() {
        //1. 定义key
        String key = SystemConstants.REDISKEY_CHANNELLIST;
        //2. 查询redis
        String channelListJson = stringRedisTemplate.opsForValue().get(key);
        List<AdChannel> channelList = new ArrayList<>();
        //3. 判断是否为空值
        if(null == channelListJson) {
            //4. 为空值，就得远程调用admin查询
            ResultVo<List<AdChannel>> resultVo = adChannelFeign.listAll();
            //4.1 解析返回的结果值
            if(!resultVo.isSuccess()){
                throw new LeadNewsException("查询频道列表失败!");
            }
            channelList = resultVo.getData();// 有可能是null
            //4.2 如果结果没数据则存入redis,数据为[]，设置有效期10秒
            if(CollectionUtils.isEmpty(channelList)){
                channelList = new ArrayList<>();
                String json = JSON.toJSONString(channelList); // []
                //则存入redis,数据为[]，设置有效期10秒
                stringRedisTemplate.opsForValue().set(key, json, 10, TimeUnit.SECONDS);
            }else {
                //4.3 如果结果有数据则要存入redis
                String json = JSON.toJSONString(channelList);
                stringRedisTemplate.opsForValue().set(key, json);
            }
        }else{
            // 转成java对象
            channelList = JSON.parseArray(channelListJson, AdChannel.class);
        }
        //5. 返回数据
        return channelList;
    }
}
